<?php
namespace Redis;

class Redis
{
    private static $handler   = null;
    private static $_instance = null;
    //默认配置
    private static $options = [
        'host'       => '127.0.0.1',
        'port'       => 6379,
        'password'   => '',
        'select'     => 0,
        'timeout'    => 0,
        'expire'     => 0,
        'persistent' => false,
        'prefix'     => '',
    ];

    public function __construct($options = [])
    {
        if (!extension_loaded('redis')) {
            throw new \BadFunctionCallException('not support: redis'); //判断是否有扩展
        }
        if (!empty($options)) {
            self::$options = array_merge(self::$options, $options);
        }

        $func    = self::$options['persistent'] ? 'pconnect' : 'connect'; //长链接或短链接
        $handler = new \Redis;
        $handler->connect(self::$options['host'], self::$options['port'], self::$options['timeout']);

        if ('' != self::$options['password']) {
            $handler->auth(self::$options['password']);
        }
        self::$handler = $handler;
        if (0 != self::$options['select']) {
            self::$handler->select(self::$options['select']);
        }
    }

    /**
     * @return RedisPackage|null 对象
     */
    public static function getInstance()
    {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * 禁止外部克隆
     */
    public function __clone()
    {
        trigger_error('Clone is not allow!', E_USER_ERROR);
    }

    /**
     * 获得redis实例
     *
     */

    public static function getRedisObj()
    {

        return self::$handler;
    }

}
